#include "slide-button.h"

SlideButton::SlideButton(QString image_pathname, QString sound_pathname, int slide_distance, int ratio)
{
    if (image_pathname == nullptr)
    {
        qDebug() << "image_pathname = nullptr";
        return;
    }

    this->image_pathname = image_pathname;
    this->slide_distance = slide_distance;

    // 设置按钮图片
    setButtonImage(image_pathname);

    // 设置按钮音效
    this->sound = new QSound(sound_pathname, this);
}

SlideButton::~SlideButton()
{
    delete sound;
}

bool SlideButton::event(QEvent *event)
{
    // 其他事件交给父类处理
    return QWidget::event(event);
}

void SlideButton::mousePressEvent(QMouseEvent *event)
{
    // 当前按钮在动画过程中, 拦截硬币的点击事件
    if (is_animation)
    {
        return;
    }

    this->is_animation = true;

    // 在鼠标按下时实现按钮的下坠
    downBounce();

    // 在鼠标释放时实现按钮的上升
    upBounce();

    this->sound->play();

    this->is_animation = false;

    return QPushButton::mousePressEvent(event);
}

void SlideButton::mouseReleaseEvent(QMouseEvent *event)
{
    return QPushButton::mouseReleaseEvent(event);
}

void SlideButton::downBounce(){
    // 1. 创建动画对象
    QPropertyAnimation* animation = new QPropertyAnimation(this, "geometry");

    // 2. 设置动画时间间隔(毫秒)
    animation->setDuration(200);

    // 3. 起始位置
    animation->setStartValue(QRect(this->x(), this->y(), this->width(), this->height()));

    // 4. 结束位置
    animation->setEndValue(QRect(this->x(), this->y() + slide_distance, this->width(), this->height()));

    // 5. 设置弹跳曲线
    animation->setEasingCurve(QEasingCurve::OutBounce);

    // 6. 执行动画
    animation->start();
}
void SlideButton::upBounce(){
    // 1. 创建动画对象
    QPropertyAnimation* animation = new QPropertyAnimation(this, "geometry");

    // 2. 设置动画时间间隔(毫秒)
    animation->setDuration(200);

    // 3. 起始位置
    animation->setStartValue(QRect(this->x(), this->y() + slide_distance, this->width(), this->height()));

    // 4. 结束位置
    animation->setEndValue(QRect(this->x(), this->y(), this->width(), this->height()));

    // 5. 设置弹跳曲线
    animation->setEasingCurve(QEasingCurve::OutBounce);

    // 6. 执行动画
    animation->start();
}

void SlideButton::setButtonImage(QString image_pathname)
{
    QPixmap pixmap;
    bool result = pixmap.load(image_pathname);

    if(!result) {
        qDebug() << "加载图片 " << image_pathname << " 失败!";
        return;
    }

    // 设置图片缩放比
    pixmap = pixmap.scaled(pixmap.width() * 0.9, pixmap.height() * 0.9);

    // 设置图片固定大小
    this->setFixedSize(pixmap.size());

    // 设置不规则图片样式
    this->setStyleSheet("QPushButton{border:0px;}");

    // 设置图标
    this->setIcon(pixmap);

    // 设置图标大小
    this->setIconSize(pixmap.size());
}
